from sanic.views import HTTPMethodView
from sanic.response import text,json
import urllib3
from processing.other_func import Random_id
import json as jn

from processing.Sql_DataFrom import ProJosn

class wechatLogin(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        html_data = request.json
        client_ip = request.ip
        appid = 'wx5ad1de89ad1ea149'
        user_id = request.app.ctx.user_id
        appsecret = '016b50a4bb754f24e293767d006e0c22'
        openid = ''

        try:
            # 查询商家
            sql = """
                    select user_id,wx_config from a_users where user_id=%s and status='normal'
                """

            user_id = db.find_one(sql, (user_id))
            # print(user_id)
            wx_config = user_id[1]
            user_id = user_id[0]

            if wx_config:
                wx_config = jn.loads(wx_config)
                appid = wx_config['appId']
                appsecret = wx_config['appSecret']

            if user_id:

                # 微信接口服务地址
                base_url = 'https://api.weixin.qq.com/sns/jscode2session'
                # 微信接口服务的带参数的地址
                url = base_url + "?appid=" + appid + "&secret=" + appsecret + "&js_code=" + html_data[
                    'code'] + "&grant_type=authorization_code"
                http = urllib3.PoolManager()
                resp = jn.loads(http.request('GET', url).data)
                openid = resp['openid']

                # 查询用户是否注册
                sql_register = """
                   select openid,nickName,head_img,phone,config from c_users where merchant_id=%s and openid=%s and status='normal'
               """

                register_show = db.find_one(sql_register, (user_id, openid))

                if register_show:
                    # 查询余额
                    sql = f"""
                         select sum(residue) from rechargerecord where merchant_id='{user_id}' and status='normal' and openid='{register_show[0]}' and paymentStatus='1'
                     """
                    monery = db.find_one(sql)
                    userInfo = {
                        'openid':register_show[0],
                        'nickName':register_show[1],
                        'head_img':register_show[2],
                        'phone':register_show[3],
                        'config': register_show[4],
                        'user_monery': monery[0]
                    }

                    return json({
                        'code': 200,
                        'message': "登录成功！",
                        'data':{
                            'userInfo':userInfo
                        }
                    })
                else:
                    wechat_sql_insert = """
                            insert into c_users(password,user_id,merchant_id,openid,nickName,age,gender,head_img,phone,config,status,create_time ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
                        """
                    password = Random_id(16, 'PASSWORD')
                    c_user_id = Random_id(32,'CUSERID')
                    db.insert(wechat_sql_insert, (password,c_user_id,user_id, openid, '微信用户', '0', '0',
                      'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F9e8bd863-bf16-4647-abf0-88490ce78ced%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1692239797&t=a656713f3185954147d0d361bef4b02d',
                      '', '', 'normal'
                      ))

                    sql_register = """
                       select openid,nickName,head_img,phone,config from c_users where merchant_id=%s and openid=%s and status='normal'
                   """

                    register_show = db.find_one(sql_register, (user_id, openid))

                    # 查询余额
                    sql = f"""
                        select sum(residue) from rechargerecord where merchant_id='{user_id}' and status='normal' and openid='{register_show[0]}' and paymentStatus='1'
                    """
                    monery = db.find_one(sql)
                    userInfo = {
                        'openid': register_show[0],
                        'nickName': register_show[1],
                        'head_img': register_show[2],
                        'phone': register_show[3],
                        'config': register_show[4],
                        'user_monery': monery[0],
                    }
                    return json({
                        'code': 200,
                        'message': "注册成功！",
                        'data': {
                            'userInfo': userInfo
                        }
                    })
            else:
                return json({'code': 401, 'message': "授权码无效！"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/wechat/wxlogin', error))
            if openid:
                return json({'code': 500, 'message': "后端代码出错！"})
            else:
                return json({'code': 500, 'message': "appid或serct不对！"})


class h5Login(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        html_data = request.json
        client_ip = request.ip
        merchant_id = request.app.ctx.user_id

        if html_data['status'] ==False:

            sql = f"""
                    select openid,nickName,head_img,phone,config from c_users where merchant_id='{merchant_id}' and status='normal' and password='{html_data["password"]}'
                """

            for i in list(html_data):
                if i == 'phone':
                    sql += f" and phone='{html_data['phone']}' "
                elif i == 'nickName':
                    sql += f" and nickName='{html_data['nickName']}' "
            data = db.find_one(sql)

            if data:

                # 查询余额
                sql = f"""
                         select sum(residue) from rechargerecord where merchant_id='{merchant_id}' and status='normal' and openid='{data[0]}' and paymentStatus='1'
                     """
                monery = db.find_one(sql)

                userInfo = {
                    'openid': data[0],
                    'nickName': data[1],
                    'head_img': data[2],
                    'phone': data[3],
                    'config': data[4],
                    'user_monery': monery[0],
                }
                return json({
                    'code': 200,
                    'message': "登录成功！",
                    'data': {
                        'userInfo': userInfo
                    }
                })
            else:
                return json({
                    'code': 201,
                    'message': "账号或密码不正确！",
                })
        else:

            find_sql = f"""
                select * from c_users where merchant_id='{merchant_id}' and phone='{html_data['phone']}'
            """

            find_data = db.find_one(find_sql)

            if find_data:
                return json({
                    'code': 201,
                    'message': "账号已存在！",
                })
            else:


                find_insert = f"""
                   insert into c_users(merchant_id,openid,nickName,head_img,phone
                   ,user_id,status,password,create_time
                   ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,now())
                """
                c_user_id = Random_id(32, 'CUSERID')
                db.insert(find_insert,(
                    merchant_id,
                    c_user_id,
                    '微信用户',
                    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F9e8bd863-bf16-4647-abf0-88490ce78ced%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1692239797&t=a656713f3185954147d0d361bef4b02d',
                    html_data['phone'],
                    c_user_id,
                    'normal',
                    html_data['password']
                ))

                return json({
                    'code': 200,
                    'message': "注册成功！",
                })
class h5LoginRefresh(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        html_data = request.json
        client_ip = request.ip
        merchant_id = request.app.ctx.user_id

        sql = f"""
            select openid,nickName,head_img,phone,config from c_users where merchant_id='{merchant_id}' and status='normal' and openid='{html_data["openid"]}'
        """

        data = db.find_one(sql)

        if data:

            # 查询余额
            sql = f"""
                     select sum(residue) from rechargerecord where merchant_id='{merchant_id}' and status='normal' and openid='{data[0]}' and paymentStatus='1'
                 """
            monery = db.find_one(sql)

            userInfo = {
                'openid': data[0],
                'nickName': data[1],
                'head_img': data[2],
                'phone': data[3],
                'config': data[4],
                'user_monery': monery[0] or 0,
            }
            return json({
                'code': 200,
                'message': "登录成功！",
                'data': {
                    'userInfo': userInfo
                }
            })
        else:
            return json({
                'code': 201,
                'message': "账号或密码不正确！",
            })


class getWechatConfig(HTTPMethodView):
    async def post(self, request):
        client_ip = request.ip
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        sql = f"""
            select wx_config from a_users where user_id='{user_id}'
        """

        sql_theme = f"""
               select main_color,assist_color,type,main_font_color,font_assist,tabbar,typeface,tabbarColor from theme where merchant_id='{user_id}'
           """
        userData = db.find_one(sql)
        themeData = db.find_all(sql_theme)
        if userData and themeData:
            themeData = ProJosn(themeData, sql_theme)
            return json({
                'code': 200,
                'message': "请求成功！",
                'data':{
                    'theme_config':themeData[0],
                    'wx_config':userData[0]
                }
            })
        else:
            return json({
                'code': 201,
                'message': "未查询到！",
            })
